import axios from 'axios'
import { Loading, Message } from 'element-ui'

let loading
let loadingCount = 0
export function request (config) {
  const instance1 = axios.create({
    baseURL: '/api',
    timeout: 30000
  })
  // 请求拦截和响应拦截
  instance1.interceptors.request.use(config => {
    showMask()
    return config
  })
  instance1.interceptors.response.use(
    res => {
      closeMask()
      return res.data
    },
    err => {
      closeMask()
      Message.error(err.response.data.message)
      throw err
    }
  )
  return instance1(config)
}

function showMask () {
  loading = Loading.service({
    target: 'body',
    background: 'transparent',
    text: '载入中'
  })
  loadingCount++
}
function closeMask () {
  loadingCount--
  if (loadingCount === 0) {
    loading.close()
    loading = null
  }
}
